<?php
include_once('config/config.php');

// 接收参数
$action = isset($_POST['action']) ? trim($_POST['action']) : '';

if($action === 'admin_username_select')
{
    // 接收用户名
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';

    // 查询数据表是否存在该用户名
    $sql = "SELECT * FROM `pre_admin` WHERE `username` = '$username'";

    // 执行Sql语句
    $result = mysqli_query($conn,$sql);

    $info = [];

    // 如果查询到有数据返回的就把数据提取出来赋值info变量
    if($result && mysqli_num_rows($result) > 0)
    {
        $info = mysqli_fetch_assoc($result);
    }

    if($info)
    {
        echo json_encode(['code' => 0,'msg' => '用户名已存在','data' => null]);
        exit;
    }else{
        echo json_encode(['code' => 1,'msg' => '用户名可用','data' => null]);
        exit;
    }
}

if($action === 'logout')
{
    setcookie('auth','',time() - 1);

    echo json_encode(['code' => 1,'msg' => '退出当前账号成功 ','data' => null]);
    exit;
}

if($action === 'person_del')
{
    $id = isset($_POST['id']) ? trim($_POST['id']) : 0;

    $PersonSql = "SELECT * FROM `pre_person` WHERE `id` = '$id'";

    $person = find($PersonSql);

    if(!$person)
    {
        echo json_encode(['code' => 0,'msg' => '该员工不存在','data' => null]);
        exit;
    }

    $result = del('person',"`id` = '$id'");

    if($result['code'] === 1)
    {
        @is_file('.' . $person['avatar']) && unlink('.' . $person['avatar']);

        echo json_encode(['code' => 1,'msg' => '删除成功','data' => null]);
        exit;
    }else{
        echo json_encode(['code' => 0,'msg' => '删除失败','data' => null]);
        exit;
    }
}

if($action === 'select_job')
{
    $depid = isset($_POST['depid']) ? trim($_POST['depid']) : 0;

    // 判断这个部门是否存在
    $DepSql = "SELECT * FROM `pre_department` WHERE `id` = '$depid'";

    $DepInfo = find($DepSql);

    if(!$DepInfo)
    {
        echo json_encode(['code' => 0,'msg' => '部门不存在','data' => null]);
        exit;
    }

    $JobSql = "SELECT * FROM `pre_job` WHERE `depid` = '$depid'";

    $JobData = all($JobSql);

    if($JobData)
    {
        echo json_encode(['code' => 1,'msg' => '查询数据成功','data' => $JobData]);
        exit;
    }else{
        echo json_encode(['code' => 0,'msg' => '暂无职位','data' => null]);
        exit;
    }
}